#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include "log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;
int main()
{
    std::string ip("192.168.8.16");
    uint16_t port = 8080;
    InetAddr peer(port, ip);
    
    //创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        LOG((int)LogLevel::FATAL) << "服务端套接字创建失败！";
        exit(SOCKET_ERR);
    }
    //std::cout << peer.AddrMessage() << std::endl;

    //连接服务器
    int n = connect(sockfd, peer.Sockaddr(), peer.Socklen());
    if(n < 0)
    {
        LOG((int)LogLevel::FATAL) << "服务端连接失败！";
        exit(CONNECT_ERR);
    }

    while(true)
    {
        std::string sdMessage;
        std::cout << "请输入：" << std::endl;
        getline(std::cin, sdMessage);
        int w = write(sockfd, sdMessage.c_str(), sdMessage.size());
        if(w < 0)
        {
            LOG((int)LogLevel::FATAL) << "服务端写入失败！";
            exit(WRITE_ERR);
        }

        char rcMessage[1024];
        int r = read(sockfd, rcMessage, sizeof(rcMessage));
        if(r < 0)
        {
            LOG((int)LogLevel::FATAL) << "服务端读取失败！";
            exit(READ_ERR);
        }
        rcMessage[r] = 0;
        std::string message("server Say#");
        message += rcMessage;
        std::cout << message << std::endl;
    }
    return 0;
}